package com.example.demotest.service;

import com.example.demotest.pojo.Order;
import com.example.demotest.pojo.OrderAddress;
import com.example.demotest.pojo.OrderStatus;
import com.example.demotest.pojo.Product;
import com.example.demotest.pojo.ProductSoldStatus;
import com.example.demotest.pojo.dto.*;
import com.example.demotest.repository.OrderAddressRepository;
import com.example.demotest.repository.OrderRepository;
import com.example.demotest.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.List;
import java.util.Optional;

@Service
public class OrderService implements IOrderService {
    private final OrderRepository orderRepository;
    private final ProductRepository productRepository;
    private final OrderAddressRepository orderAddressRepository;

    @Autowired
    public OrderService(OrderRepository orderRepository,
                        ProductRepository productRepository,
                        OrderAddressRepository orderAddressRepository) {
        this.orderRepository = orderRepository;
        this.productRepository = productRepository;
        this.orderAddressRepository = orderAddressRepository;
    }

    @Transactional
    @Override
    public Order createOrder(Integer buyerId, OrderCreateDto orderDto) {
        Product product = productRepository.findById(orderDto.getProductId())
                .orElseThrow(() -> new RuntimeException("商品不存在"));

        Order newOrder = new Order();
        newOrder.setProductId(product.getProductID());
        newOrder.setBuyerId(buyerId);
        newOrder.setSellerId(product.getUserId());
        newOrder.setQuantity(orderDto.getQuantity());
        newOrder.setTotalPrice(BigDecimal.valueOf(product.getProductPrice() * orderDto.getQuantity()));
        newOrder.setOrderStatus(0);
        newOrder.setPaymentStatus(0);
        // 设置图片
        if (orderDto.getImages() != null && !orderDto.getImages().isEmpty()) {
            newOrder.setImageList(orderDto.getImages());
        } else if (product.getImages() != null && !product.getImages().isEmpty()) {
            // 如果订单DTO中没有图片，则使用商品的图片
            newOrder.setImages(product.getImages());
        }
        LocalDateTime now = LocalDateTime.now();
        newOrder.setCreatedAt(now);
        newOrder.setUpdatedAt(now);

        // 将商品状态改为下架
        product.setStatusSold(ProductSoldStatus.OFF_SALE);
        productRepository.save(product);
        System.out.println(newOrder);
        Order savedOrder = orderRepository.save(newOrder);
        saveOrderAddress(savedOrder.getOrderId(), orderDto);
        System.out.println(savedOrder);
        return savedOrder;
    }

    @Override
    @Transactional(readOnly = true)
    public OrderDetailDto getOrderDetail(Integer orderId, Integer userId) {
        Order order = orderRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));

        Product product = productRepository.findById(order.getProductId())
                .orElseThrow(() -> new RuntimeException("商品不存在"));

        OrderDetailDto detail = new OrderDetailDto();
        detail.setId(order.getOrderId());
        detail.setOrderNumber("ORD" + order.getOrderId());
        detail.setOrderStatus(order.getOrderStatus());
        detail.setOrderPrice(order.getTotalPrice());
        detail.setBuyerId(order.getBuyerId());
        detail.setSellerId(order.getSellerId());
        detail.setQuantity(order.getQuantity());
        detail.setCreateTime(order.getCreatedAt());
        detail.setPaymentWay(order.getPaymentMethod());
        detail.setPaymentStatus(order.getPaymentStatus());
        detail.setOrderAddress(getOrderAddressDTO(orderId));

        IdleItemDTO idleItem = new IdleItemDTO();
        idleItem.setId(product.getProductID().toString());
        idleItem.setIdleName(product.getProductName());
        idleItem.setIdlePrice(product.getProductPrice());
        idleItem.setImgUrl(getFirstImage(product.getImages()));
        detail.setIdleItem(idleItem);

        return detail;
    }

    @Transactional
    @Override
    public boolean payOrder(Integer orderId, Integer userId, OrderPayDto payDto) {
        Order order = orderRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));

        if (!order.getBuyerId().equals(userId)) {
            throw new RuntimeException("无权操作此订单");
        }

        if (order.getOrderStatus() != 0) {
            throw new RuntimeException("订单状态异常，无法支付");
        }

        order.setOrderStatus(1);
        order.setPaymentStatus(1);
        order.setPaymentMethod(payDto.getPaymentWay());
        order.setTransactionId(payDto.getTransactionId());
        order.setPaymentTime(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());

        orderRepository.save(order);
        return true;
    }

    @Transactional
    @Override
    public boolean updateOrderStatus(Integer orderId, Integer operatorId, OrderStatusDto statusDto) {
        Order order = orderRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));

        int currentStatus = order.getOrderStatus();
        int newStatus = statusDto.getOrderStatus();

        // 验证状态转换的合法性
        if (currentStatus == 2 && newStatus == 3) {
            // 待收货 -> 已完成：买家确认收货
            if (!order.getBuyerId().equals(operatorId)) {
                throw new RuntimeException("只有买家可以确认收货");
            }
            // 确保商品状态为下架
            Product product = productRepository.findById(order.getProductId())
                    .orElseThrow(() -> new RuntimeException("商品不存在"));
            product.setStatusSold(ProductSoldStatus.OFF_SALE);
            productRepository.save(product);
        } else if (currentStatus == 1 && newStatus == 2) {
            // 待发货 -> 待收货：卖家发货
            if (!order.getSellerId().equals(operatorId)) {
                throw new RuntimeException("只有卖家可以发货");
            }
            // 确保商品状态为下架
            Product product = productRepository.findById(order.getProductId())
                    .orElseThrow(() -> new RuntimeException("商品不存在"));
            product.setStatusSold(ProductSoldStatus.OFF_SALE);
            productRepository.save(product);
        } else if (currentStatus == 0 && newStatus == 1) {
            // 待付款 -> 待发货：支付成功
            // 确保商品状态为下架
            Product product = productRepository.findById(order.getProductId())
                    .orElseThrow(() -> new RuntimeException("商品不存在"));
            product.setStatusSold(ProductSoldStatus.OFF_SALE);
            productRepository.save(product);
        } else if (currentStatus == 0 && newStatus == 4) {
            // 待付款 -> 已取消：买家取消订单
            if (!order.getBuyerId().equals(operatorId)) {
                throw new RuntimeException("只有买家可以取消订单");
            }
            // 订单取消，恢复商品状态为上架
            Product product = productRepository.findById(order.getProductId())
                    .orElseThrow(() -> new RuntimeException("商品不存在"));
            product.setStatusSold(ProductSoldStatus.ON_SALE);
            productRepository.save(product);
        } else if (currentStatus == 1 && newStatus == 4) {
            // 待发货 -> 已取消：买家取消订单
            if (!order.getBuyerId().equals(operatorId)) {
                throw new RuntimeException("只有买家可以取消订单");
            }
            // 订单取消，恢复商品状态为上架
            Product product = productRepository.findById(order.getProductId())
                    .orElseThrow(() -> new RuntimeException("商品不存在"));
            product.setStatusSold(ProductSoldStatus.ON_SALE);
            productRepository.save(product);
        } else {
            throw new RuntimeException("非法状态流转：当前状态 " + currentStatus + " 不能转换为 " + newStatus);
        }

        // 更新订单状态
        order.setOrderStatus(newStatus);
        order.setUpdatedAt(LocalDateTime.now());

        try {
            orderRepository.save(order);
            return true;
        } catch (Exception e) {
            throw new RuntimeException("更新订单状态失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public boolean deleteOrder(Integer orderId, Integer userId) {
        Order order = orderRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));

        if (!order.getBuyerId().equals(userId)) {
            throw new RuntimeException("无权删除此订单");
        }

        if (order.getOrderStatus() != 0 && order.getOrderStatus() != 4 && order.getOrderStatus() != 3) {
            throw new RuntimeException("当前状态不可删除");
        }

        orderRepository.delete(order);
        return true;
    }

    @Override
    public boolean isSellerOrAdmin(Integer orderId, Integer userId) {
        Order order = orderRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));
        return order.getSellerId().equals(userId);
    }

    private void saveOrderAddress(Integer orderId, OrderCreateDto orderDto) {
        OrderAddress address = new OrderAddress();
        address.setOrderId(orderId);
        address.setConsigneeName(orderDto.getConsigneeName());
        address.setConsigneePhone(orderDto.getConsigneePhone());
        address.setProvince(orderDto.getProvince());
        address.setCity(orderDto.getCity());
        address.setDistrict(orderDto.getDistrict());
        address.setDetailAddress(orderDto.getDetailAddress());
        address.setPostalCode(orderDto.getPostalCode());
        orderAddressRepository.save(address);
    }

    private OrderAddressDTO getOrderAddressDTO(Integer orderId) {
        OrderAddress address = orderAddressRepository.findByOrderId(orderId)
                .orElseThrow(() -> new RuntimeException("订单地址不存在"));

        OrderAddressDTO dto = new OrderAddressDTO();
        dto.setId(address.getId());
        dto.setOrderId(address.getOrderId());
        dto.setConsigneeName(address.getConsigneeName());
        dto.setConsigneePhone(address.getConsigneePhone());
        dto.setProvince(address.getProvince());
        dto.setCity(address.getCity());
        dto.setDistrict(address.getDistrict());
        dto.setDetailAddress(address.getDetailAddress());
        dto.setPostalCode(address.getPostalCode());
        dto.setCreatedAt(address.getCreatedAt());
        return dto;
    }

    private String getFirstImage(String imagesStr) {
        if (imagesStr == null || imagesStr.isEmpty()) return "";
        String[] imgList = imagesStr.split(",");
        return imgList.length > 0 ? imgList[0] : "";
    }

    @Override
    public Map<String, Object> getOrderList(Integer page, Integer nums, String sort) {
        // 创建分页对象
        Pageable pageable;
        if (sort != null && sort.contains("createTime,desc")) {
            pageable = PageRequest.of(page - 1, nums, Sort.by(Sort.Direction.DESC, "createTime"));
        } else {
            pageable = PageRequest.of(page - 1, nums);
        }

        // 获取分页数据
        Page<Order> orderPage = orderRepository.findAll(pageable);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", orderPage.getContent());
        result.put("count", orderPage.getTotalElements());

        return result;
    }

    @Override
    public List<Order> getMyOrders(Integer userId) {
        return orderRepository.findByBuyerId(userId);
    }

    @Override
    public List<Order> getMySoldOrders(Integer userId) {
        return orderRepository.findBySellerId(userId);
    }

    @Override
    public List<Order> findOrdersByStatus(OrderStatus status) {
        return orderRepository.findByOrderStatus(status.getCode());
    }

    @Override
    public List<Order> findOrdersByRiderId(Integer riderId) {
        return orderRepository.findByRiderId(riderId);
    }

    @Override
    public Order getOrderById(Integer orderId) {
        return orderRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在，ID：" + orderId));
    }

    @Override
    public Order save(Order order) {
        return orderRepository.save(order);
    }

    @Override
    public boolean updateOrderStatus(Integer orderId, OrderStatus newStatus) {
        Optional<Order> optionalOrder = orderRepository.findById(orderId);
        if (optionalOrder.isPresent()) {
            Order order = optionalOrder.get();
            order.setOrderStatus(newStatus.getCode());
            orderRepository.save(order);
            return true;
        }
        return false;
    }

    @Override
    public List<Order> getAvailableOrders() {
        return orderRepository.findByOrderStatusAndDeliveryStatus(
                OrderStatus.WAIT_SHIP.getCode(),
                Order.DeliveryStatus.WAITING_FOR_PICKUP
        );
    }
}